﻿using ApplicationLibrary.SqlConnector;
using Plumber.Masters.ModuleData;

namespace Plumber.Masters.Library
{
    internal class EmailAddressLoader
    {
        private DRMasterType drMasterType = new DRMasterType(DRMasterType.Module.Master);
        private DRMasterTypeByType drMasterTypeType = new DRMasterTypeByType();

        public void LoadAddress(ApplicationLibrary.Emailer.emailAddress ea)
        {
            QueryBuilder qb = new QueryBuilder();
            qb.AddSelectAll(PL_Masters.Name);
            qb.AddFrom(PL_Masters.Name);
            qb.AddCompare<string>(PL_Masters.Email, "", "!=");
            qb.AddOrder(PL_Masters.Type);
            qb.AddOrder(PL_Masters.Code);

            SqlABCommand scc = new SqlABCommand();
            scc.CommandText = qb.Query;

            SqlABDataReader dr = scc.ExecuteReader();
            string oldtype = string.Empty;
            drMasterTypeType.Find(MasterTypes.E_Condominium);

            ea.ClearData();
            while (dr.Read())
            {
                if (oldtype != dr.GetValue<string>(PL_Masters.Type))
                {
                    drMasterType.Find(dr.GetValue<string>(PL_Masters.Type));
                    oldtype = dr.GetValue<string>(PL_Masters.Type);
                }
                string type = drMasterType.GetValue<string>(PL_MasterType.Description);
                string description = dr.GetValue<string>(PL_Masters.Type) == drMasterTypeType.GetValue<string>(PL_MasterType.Code)
                                    ? dr.GetValue<string>(PL_Masters.Address)
                                    : dr.GetValue<string>(PL_Masters.Description);

                string email = dr.GetValue<string>(PL_Masters.Email);

                ea.AddAddress(type, description, email);
            }
            dr.Close();
            ea.SetColumnSize();
        }
    }
}